package com.lfz.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 通过缓存键 key 获取 redis缓存数据
     * @param key   缓存键
     * @return
     */
    public Object get(String key) {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            if (value != null) {
                logger.info("从 Redis 获取缓存数据，键: {}", key);
            } else {
                logger.info("Redis 中未找到缓存数据，键: {}", key);
            }
            return value;
        } catch (Exception e) {
            logger.error("Redis连接失败，降级到MySQL: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 设置 redis缓存
     * @param key   缓存键
     * @param value 缓存值
     * @param ttl   缓存时间
     */
    public void set(String key, Object value, long ttl) {
        try {
            // 确保值不为null
            if (value != null) {
                redisTemplate.opsForValue().set(key, value, ttl, TimeUnit.MINUTES);
                logger.info("将数据存入 Redis 缓存，键: {}", key);
            }
        } catch (Exception e) {
            logger.error("Redis缓存设置失败: {}", e.getMessage());
            logger.error("将数据存入 Redis 缓存时出错，键: {}", key, e);
        }
    }

    public void delete(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error("Redis缓存删除失败: {}", e.getMessage());
        }
    }

    // 批量删除通配符key
    public void deletePattern(String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern);
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
            }
        } catch (Exception e) {
            logger.error("Redis批量删除失败: {}", e.getMessage());
        }
    }
}